package com.mtor.applicationadmin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ApplicationAdmin extends Activity {
	ApplicationAdmin curActivity = this;
	private String selectPackageName="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.application_admin);
		
		PackageManager packagemanager = getPackageManager();
		final List<PackageInfo> appList = packagemanager.getInstalledPackages(0);
		ArrayAdapter<PackageInfo>adaptedAppList = 
				new ArrayAdapter<PackageInfo>(this, android.R.layout.simple_list_item_single_choice, appList);
		ListView listView = (ListView)findViewById(R.id.app_list);
		listView.setAdapter(adaptedAppList);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		
		//리스트뷰에서 선택된 항목의 패키지 이름만 저장
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
				final PackageInfo runApp = appList.get(arg2);
				selectPackageName = runApp.packageName;
//				AlertDialog.Builder alertDialog = new AlertDialog.Builder(curActivity);
//				alertDialog.setTitle("어플리케이션 제거 ");
//				alertDialog.setMessage("선택한 어플리케이션 ("+ runApp.packageName+")을 제거하시겠습니까?");
//				alertDialog.setPositiveButton("예", new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						Uri uri = Uri.fromParts("package", runApp.packageName, null);
//						Intent it = new Intent(Intent.ACTION_DEFAULT, uri);
//						startActivity(it);
//					}
//				});
//				alertDialog.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						
//					}
//				});
//				alertDialog.show();
			}
		});
	}
		
	//선택된 항목의 패키지를 복사함수
	public void fileCopy(String src, String dest){
		try{
			InputStream myInput = new FileInputStream(src);
			OutputStream myOutput = new FileOutputStream(dest);
			byte[] buffer = new byte[1024];
			
			int totla_length = 0;
			int length;
			while((length = myInput.read(buffer)) > 0){
				myOutput.write(buffer, 0, length);
				totla_length+=length;
			}
			totla_length+=length;
			
			myOutput.flush();
			myOutput.close();
			myInput.close();
		}
		catch(Exception e){
			Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
		}
	}
	
	//res/memu/munu.xml파일을 사용할 메뉴로 지정
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.application_admin, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.backup :
		{
			if(selectPackageName.length() > 0) {
				//String srcFile = "/data/app/"+selectPackageName + ".apk";
				String srcFile = "/storage/sdcard0/Adnroid/data/"+selectPackageName + ".apk";
				//String destFile = "/sdcard/"+selectPackageName + ".apk";
				String destFile = "/storage/sdcard0/jkbae/"+selectPackageName + ".apk";
				
				try{
					File file = new File(srcFile);
					if(file.isFile()){
						fileCopy(srcFile, destFile);
						Toast.makeText(getBaseContext(), selectPackageName + "을 백업했습니다.", Toast.LENGTH_SHORT).show();
					}
					else {
						Toast.makeText(getBaseContext(), "해당 어플리케이션은 백업할 수 없습니다.", Toast.LENGTH_SHORT).show();
					}
				}
				catch(Exception e){
					Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
				}
			}
			else 
				Toast.makeText(getBaseContext(), "백업할  어플리케이션을 선택하세요", Toast.LENGTH_SHORT).show();
		}
		return true;
		
		case R.id.uninstall:
		{
			if (selectPackageName.length() > 0){
   				AlertDialog.Builder alertDialog = new AlertDialog.Builder(curActivity);
				alertDialog.setTitle("어플리케이션 제거");
				alertDialog.setMessage("선택한 어플리케이션("+selectPackageName+")을 제거하시겠습니까?");
				alertDialog.setPositiveButton("예", 
	   				new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							Uri uri = Uri.fromParts("package", selectPackageName, null);
					        Intent it = new Intent(Intent.ACTION_DELETE, uri);
					        startActivity(it); 
						}
					});
				alertDialog.setNegativeButton("아니오", 
	   				new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
						}
					});
				alertDialog.show();   		
			}
			
		}
		return true;
		} // switch
		return super.onOptionsItemSelected(item);
	}


}
